﻿Imports ajayumi.develop.win32.GRssReader.Service.Model
Imports System.Xml
Imports System.ServiceModel.Syndication
Imports System.IO
Imports System.Net
Imports System.ComponentModel
Imports System.Text
Imports ajayumi.develop.VBasic.Core

Public Class OnlineFeedService
    Inherits FeedServiceBase

#Region "Variables"
    Private m_Node As TreeNode = Nothing
    Private m_DownloadManager As DownloadManager = Nothing
    Private ReadOnly m_LockObject As Object = Nothing
#End Region

#Region "Properties"
    Public ReadOnly Property [Node]() As TreeNode
        Get
            Return Me.m_Node
        End Get
    End Property

#End Region

    Public Sub New(node As TreeNode, subscriptionInfo As SubscriptionInfo)
        MyBase.New(subscriptionInfo)
        Me.m_Node = node

        Me.m_DownloadManager = New DownloadManager()
        AddHandler Me.m_DownloadManager.DownloadProgressChanged, AddressOf Me.DownloadManager_DownloadProgressChanged

        Me.m_LockObject = New Object()
    End Sub

    Public Overrides Sub Clear()
        SyncLock Me.m_LockObject
            Dim _Directory As String = GetSubscriptionImageCacheFolder(Me.SubscriptionInfo)
            Directory.Delete(_Directory, True)
        End SyncLock
    End Sub


    Public Overloads Overrides Sub GetArticleInfos(count As Integer)
        Dim _Error As Exception = Nothing
        SyncLock Me.m_LockObject
            If count > 0 Then
                Try
                    Dim _ArticleInfos As IEnumerable(Of ArticleInfo) = o_ReaderService.GetArticleInfos(SubscriptionInfo, count)

                    Me.saveArticles(_ArticleInfos)
                Catch ex As Exception
                    _Error = ex
                End Try
            End If

            Me.OnGetArticleCompleted(New GetArticleInfoListCompleted(Me.m_ArticleInfoList, _Error, False, Me))
        End SyncLock
    End Sub

    Protected Overrides Sub Dispose(disposing As Boolean)
        If disposing Then
            Me.m_DownloadManager.Dispose()
            Me.m_DownloadManager = Nothing
        End If
        MyBase.Dispose(disposing)
    End Sub

    ''' <summary>
    ''' 保存文章条目到本地缓存文件夹
    ''' </summary>
    ''' <param name="articleInfo"></param>
    ''' <remarks></remarks>
    Private Sub saveArticle(ByRef articleInfo As ArticleInfo)
        Dim _Content As String = articleInfo.SummayText

        For Each _ArticleImageInfo As ArticleImageInfo In articleInfo.ArticleImageInfos
            Dim _TempFileName As String = String.Format("{0}_{1}_{2}{3}", _
                                             StringHelper.FilterInvalidChars(articleInfo.TitleText), _
                                             StringHelper.FilterInvalidChars(Path.GetFileNameWithoutExtension(_ArticleImageInfo.AddressText)), _
                                             articleInfo.LastUpdatedTime.ToString("yyyyMMdd"), _
                                             ".tmp")
            Dim _FileName As String = String.Format("{0}_{1}_{2}{3}", _
                                           StringHelper.FilterInvalidChars(articleInfo.TitleText), _
                                           StringHelper.FilterInvalidChars(Path.GetFileNameWithoutExtension(_ArticleImageInfo.AddressText)), _
                                           articleInfo.LastUpdatedTime.ToString("yyyyMMdd"), _
                                           Path.GetExtension(_ArticleImageInfo.AddressText))
            _ArticleImageInfo.LocalPath = Path.Combine(GetSubscriptionImageCacheFolder(Me.SubscriptionInfo), _FileName)
            _ArticleImageInfo.LocalTempPath = Path.Combine(GetDownloadCacheFolder(), _TempFileName)
            _ArticleImageInfo.SubscriptionTitle = Me.m_SubscriptionInfo.TitleText
            _ArticleImageInfo.ArticleTitle = articleInfo.TitleText
            _Content = _Content.Replace(_ArticleImageInfo.AddressText, _ArticleImageInfo.LocalPath)

            If File.Exists(_ArticleImageInfo.LocalPath) = False Then
                Me.m_DownloadManager.Add(_ArticleImageInfo)
            End If
        Next

        Dim _StringBuilder As New StringBuilder()
        _StringBuilder.Append("<div style='border:2px solid black;'>")
        _StringBuilder.AppendFormat("<div style='background:#000;color:#fff;padding:4px;'>{0}&nbsp;&nbsp;[{1}]</div>", _
                                    articleInfo.TitleText, _
                                    articleInfo.LastUpdatedTime.ToString("yyyy-MM-dd HH:mm:ss"))
        _StringBuilder.AppendFormat("<div style='padding:4px'>{0}</div>", _Content)
        _StringBuilder.Append("</div>")

        articleInfo.Summary = New TextSyndicationContent(_StringBuilder.ToString())
        articleInfo.SummayText = _StringBuilder.ToString()
    End Sub


    ''' <summary>
    ''' 保存Feed中的文章资源，如图片...
    ''' </summary>
    ''' <param name="articleInfos"></param>
    ''' <remarks></remarks>
    Private Sub saveArticles(articleInfos As IEnumerable(Of ArticleInfo))

        For Each _ArticleInfo As ArticleInfo In articleInfos
            Me.saveArticle(_ArticleInfo)
            Me.m_ArticleInfoList.Add(_ArticleInfo)
        Next

        Using writer As XmlWriter = XmlWriter.Create(Path.Combine(GetSubscriptionCacheFolder(Me.SubscriptionInfo), "ArticleInfos.xml"), _
                                                     New XmlWriterSettings() With {.CloseOutput = True, .Indent = True})
            o_ReaderService.Feed.Items = Me.m_ArticleInfoList
            Dim _Atom10FeedFormatter As New Atom10FeedFormatter(o_ReaderService.Feed)
            _Atom10FeedFormatter.WriteTo(writer)
        End Using

        ' TODO: 开始下载图片
        Me.m_DownloadManager.Start()
    End Sub

    Private Sub DownloadManager_DownloadProgressChanged(sender As Object, e As ProgressChangedEventArgs)
        Dim _DownloadManager As DownloadManager = DirectCast(e.UserState, DownloadManager)
        Me.OnGetArticleImageProgressChanged(New GetArticleImageProgressChangedEventArgs(Me.m_Node, e.ProgressPercentage, Me))
    End Sub



End Class
